//package com.aifund.orderservice.service.impl;
//
//import com.aifund.common.entity.AiOrder;
//import com.aifund.common.entity.AiUser;
//import com.aifund.common.entity.AiUserBindExchange;
//import com.aifund.common.enums.order.AiOrderStatusEnum;
//import com.aifund.common.enums.user.UserEnum;
//import com.aifund.orderservice.service.AiOrderService;
//import com.aifund.orderservice.service.ExchangeService;
//import com.aifund.orderservice.service.UserBindExchangeService;
//import com.aifund.orderservice.service.UserService;
//import com.aifund.orderservice.util.AiOrderUtil;
//import io.grpc.stub.StreamObserver;
//import jgrpc.Grpc;
//import jgrpc.OrderServiceGrpc;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//import pb.RpcExchangeGrpc;
//import java.math.BigDecimal;
//import java.util.ArrayList;
//import java.util.List;

//实现服务接口的类
//@Service
//public class OrderServiceGrpcApi extends OrderServiceGrpc.OrderServiceImplBase {

//    @Autowired
//    UserBindExchangeService userBindExchangeService;
//    @Autowired
//    UserService userService;
//    @Autowired
//    AiOrderService aiOrderService;
//    @Autowired
//    ExchangeService exchangeService;
//    @Autowired
//    RpcExchangeGrpc.RpcExchangeStub exchangeStub;
//    @Autowired
//    RpcExchangeGrpc.RpcExchangeBlockingStub blockingStub;
//
//    @Override
//    @Transactional
//    public void noticePlaceOrder(Grpc.NoticeOrderArgs request, StreamObserver<Grpc.NoticeOrderReply> responseObserver) {
//
//        System.out.println("下单API_KEY"+request.getApiKey());
//        System.out.println("--------------------收到下单通知--------------------");
//        BigDecimal minQty = new BigDecimal(request.getMinQty()).stripTrailingZeros(); //最小成交量
//        BigDecimal minPrice = new BigDecimal(request.getMinPrice()).stripTrailingZeros();//最小成交价
//        BigDecimal minNotional = new BigDecimal(request.getMinNotional()).stripTrailingZeros();//最小成交额
//        BigDecimal lastPrice = new BigDecimal(request.getLastPrice()).stripTrailingZeros();//成交价
//        BigDecimal storeingLocationDecimal = new BigDecimal(request.getStoringLocation()).stripTrailingZeros().setScale(3,BigDecimal.ROUND_HALF_UP);//仓位
//
//        //订单号
//        String orderNumber = request.getOrderNumber();
//
//        if(orderNumber != null&&!"".equals(orderNumber)){
//            //更新订单状态
//            AiOrder aiOrder = aiOrderService.getByOrderNumber(orderNumber);
//            if(aiOrder!=null){
//                aiOrder.setOrderStatus(AiOrderStatusEnum.FINISH.getStatus());
//                aiOrderService.save(aiOrder);
//            }
//        }
//        Long exchangeId = exchangeService.getIdByExchangeNameEn(request.getExchange());
//        if(exchangeId == null){
//            System.out.println("--------------------未找到交易所"+request.getExchange()+"--------------------");
//            return;
//        }
//        String apiKey = request.getApiKey();
//        String exchange = request.getExchange();
//            Long userId = userBindExchangeService.getUserIdByApiKeyAndExchange(apiKey, exchange);
//            AiUser user = userService.getById(userId);
//            if(user != null){
//            //交易员
//            if(user.getUserIndex().equals(UserEnum.EXCHANGE_MAN.getUserIndex())){
//                /**
//                 * 保存交易员订单信息
//                 */
//                AiOrder exchangeOrder = new AiOrder();
//                exchangeOrder.setOrderNo(AiOrderUtil.getOrderIdByTime());
//                exchangeOrder.setOrderStatus(AiOrderStatusEnum.FINISH.getStatus());
//                exchangeOrder.setExchangeId(exchangeId);
//                exchangeOrder.setTradeSide(request.getTradeSide());
//                exchangeOrder.setStoringLocation(request.getStoringLocation());
//                exchangeOrder.setSymbol(request.getSymbol());
//                exchangeOrder.setApiKey(request.getApiKey());
//                exchangeOrder.setVolume(new BigDecimal(request.getVolume()));
//                exchangeOrder.setUserId(user.getId());
//                aiOrderService.save(exchangeOrder);
//
//                List<Grpc.NoticeOrderReplyOrderItem> orderItems = new ArrayList<>();
//                //跟随伙伴们
//                List<AiUser> aiUsers = userService.getUsersByFollowMan(user.getId());
//                for(AiUser aiUser : aiUsers){
//                     //用户拥有的apiKey
//                    List<AiUserBindExchange> userBindExchangeList = userBindExchangeService.getAllByUserIdAndExchangeId(aiUser.getId(), exchangeId);
//                    for(AiUserBindExchange aiUserBindExchange : userBindExchangeList){
//                        /**
//                         * 交易币对
//                         */
//                        String symbol = request.getSymbol();
//                        String[] split = symbol.split("/");
//
//                        pb.Grpc.AccountArgs.Builder accountBuilder = pb.Grpc.AccountArgs.newBuilder();
//                        accountBuilder.setApiKey(aiUserBindExchange.getApiKey());
//                        accountBuilder.setSecretKey(aiUserBindExchange.getApiSecret());
//                        accountBuilder.setExchange(request.getExchange());
//                        accountBuilder.setApiPass(request.getApiPass());
//                        if(request.getTradeSide().equals("BUY")){
//                            accountBuilder.setMoneyName(split[1]);
//                        }else{
//                            accountBuilder.setMoneyName(split[0]);
//                        }
//                        pb.Grpc.AccountReply accountReply = blockingStub.getAccount(accountBuilder.build());
//
//                        String total = null;
//                        if(request.getTradeSide().equals("SELL")){
//                            try{
//                                total = accountReply.getSub().get(split[0]).getAmount();
//                            }catch (NullPointerException e){
//                                e.printStackTrace();
//                                break;
//                            }
//
//                        }else{
//                            total = accountReply.getTotal();
//                        }
//
//                        if(total == null){
//                            System.out.println("------交易账户未查询到无法下单------");
//                            break;
//                        }
//                        BigDecimal totalDecimal = new BigDecimal(total);
//                        //成交量/成交额
//                        String multiplyString;
//                        if(request.getTradeSide().equals("BUY")){
//                            multiplyString = totalDecimal.multiply(storeingLocationDecimal).stripTrailingZeros().setScale(8,BigDecimal.ROUND_HALF_UP).toPlainString();
//                        }else{
//                            int scale = minQty.scale();
//                            multiplyString = totalDecimal.multiply(storeingLocationDecimal).stripTrailingZeros().setScale(scale,BigDecimal.ROUND_HALF_UP).toPlainString();
//                        }
//                        BigDecimal multiply = new BigDecimal(multiplyString);
//                        if(request.getTradeSide().equals("BUY")){
//                            if(multiply.compareTo(minNotional) == -1){
//                                System.out.println("无法下单------"+"最小成交额："+minNotional+",成交额："+multiply);
//                                break;
//                            }
//                        }
//                        else{
//                            if(multiply.compareTo(minQty) == -1){
//                                System.out.println("无法下单------"+"最小成交量："+minQty+",成交量："+multiply);
//                                break;
//                            }
//                        }
//
//                        //下单
//                        //本地维护订单
//                        String orderNo = AiOrderUtil.getOrderIdByTime();
//                        AiOrder aiOrder = new AiOrder();
//                        aiOrder.setOrderNo(orderNo);
//                        aiOrder.setUserId(aiUser.getId());
//                        aiOrder.setOrderStatus(AiOrderStatusEnum.IN_DOING.getStatus());
//                        aiOrder.setExchangeId(exchangeId);
//                        aiOrder.setAmount(new BigDecimal(total));
//                        aiOrder.setVolume(multiply);
//                        aiOrder.setApiKey(aiUserBindExchange.getApiKey());
//                        aiOrder.setApiPass(request.getApiPass());
//                        aiOrder.setTradeSide(request.getTradeSide());
//                        aiOrder.setSymbol(request.getSymbol());
//                        aiOrder.setStoringLocation(request.getStoringLocation());
//                        aiOrderService.save(aiOrder);
//
//                        /**
//                         * RPC通知下单
//                         */
//                        pb.Grpc.MarketTradeArgs.Builder markOrderBuilder = pb.Grpc.MarketTradeArgs.newBuilder();
//                        markOrderBuilder.setApiKey(aiUserBindExchange.getApiKey());
//                        markOrderBuilder.setExchange(request.getExchange());
//                        markOrderBuilder.setSecKey(aiUserBindExchange.getApiSecret());
//                        markOrderBuilder.setApiPass(request.getApiPass());
//                        markOrderBuilder.setSymbol(request.getSymbol());
//                        markOrderBuilder.setTradeSide(request.getTradeSide());
//                        markOrderBuilder.setVolume(multiplyString);
//                        pb.Grpc.MarketTradeReply marketTradeReply = blockingStub.marketTrade(markOrderBuilder.build());
//                        if(marketTradeReply.getOrderId()!=null&&!marketTradeReply.equals("")){
//                            System.out.println("下单返回"+marketTradeReply.getOrderId()+"");
//                            aiOrder.setOrderStatus(AiOrderStatusEnum.FINISH.getStatus());
//                            aiOrderService.save(aiOrder);
//                        }
//                    }
//                }
//                Grpc.NoticeOrderReply.Builder replyBuilder = Grpc.NoticeOrderReply.newBuilder();
//                for(int i = 0;i<orderItems.size();i++){
//                    replyBuilder.addOrders(i, orderItems.get(i));
//                }
//                Grpc.NoticeOrderReply noticeOrderReply = replyBuilder.build();
//                //onNext()方法向客户端返回结果
//                responseObserver.onNext(noticeOrderReply);
//                //告诉客户端这次调用已经完成
//                responseObserver.onCompleted();
//            }
//            else{
//                System.out.println("--------------------下单用户为非交易员--------------------");
//            }
//        } else{
//                System.out.println("--------------------未找到下单用户--------------------");
//         }
//    }
//}
